import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  UserId: number
  Username: string
  Phone: string
  Email: string
  Avatar: string
  CreatedAt: string
  LastLoginAt: string | null
  Token: string
  TokenExpireTime: string
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string | null>(null)
  const isLoggedIn = ref(false)

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    token.value = info.Token
    isLoggedIn.value = true
    localStorage.setItem('userInfo', JSON.stringify(info))
    localStorage.setItem('token', info.Token)
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    token.value = null
    isLoggedIn.value = false
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
  }

  // 从本地存储恢复用户信息
  const restoreUserInfo = () => {
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedToken = localStorage.getItem('token')
    
    if (storedUserInfo && storedToken) {
      try {
        const userInfoData = JSON.parse(storedUserInfo) as UserInfo
        userInfo.value = userInfoData
        token.value = storedToken
        isLoggedIn.value = true
      } catch (error) {
        console.error('解析用户信息失败:', error)
        clearUserInfo()
      }
    }
  }

  // 检查token是否过期
  const isTokenExpired = (): boolean => {
    if (!userInfo.value?.TokenExpireTime) return true
    
    const expireTime = new Date(userInfo.value.TokenExpireTime)
    const now = new Date()
    
    return now > expireTime
  }

  // 初始化时恢复用户信息
  restoreUserInfo()

  return {
    userInfo,
    token,
    isLoggedIn,
    setUserInfo,
    clearUserInfo,
    restoreUserInfo,
    isTokenExpired
  }
}) 